var editor;
KindEditor.ready(function(K) {
    editor = K.create('#txt_answner', {
        themeType : 'default',
        resizeType : 1,
        urlType : 'domain',
        shadowMode : false,
        allowPreviewEmoticons : false,
        allowImageUpload : true,
        allowFlashUpload : false,
        uploadJson : js_param.upload_url,
        afterCreate : function() {
            K.ctrl(this.edit.iframe.get(0).contentWindow.document, 13,
                function() {
                    $("#txt_answner").parent().submit();
                });
        },
        afterChange : function() {
            this.sync();
        },
        items : [ 'bold', 'italic', 'underline', 'strikethrough',
            'removeformat', '|', 'insertorderedlist',
            'insertunorderedlist', 'forecolor', 'hilitecolor', 'fontname',
            'fontsize', '|', 'link', 'unlink', 'image', 'flash', 'quote',
            '|', 'about' ]
    });
});

var issue_view = function() {
    var grid_id='issue_comment_grid';
    var kindeditor=null;
    var labels = $('#issue_labels').layer({
        singleton : true,
        width : 150,
        target : self
    });
    var assign_div;
    var priopities = $('#priopity_change_div').layer({
        singleton : true,
        width : 150,
        target : self
    });


    var reopen_issue = function() {
        // 重新打开问题
        cdms.common.confirm(language.issue.reopen_tip_msg, function() {
            cdms.common.ajax_get(js_param.reopen_issue_url + js_param.issue_id,
                function(data) {
                    window.location.reload();
                });
        })
    };
    var fix_comment_layer = $("#issue_fix_comment_back").layer({title : language.issue.issue_colse_comment,width : "550px",height : "350px",singleton: true});
    var close_comment_layer = $("#issue_close_comment_back").layer({title : language.issue.issue_colse_comment,width : "550px",height : "350px",singleton: true});

    return {
        label_f_click : function(dom_id, desc) {
            $("#label_desc_record").attr("value", desc);
            var current = $('#' + dom_id);
            var linek = $('#' + dom_id + '_link');
            linek.addClass("selected");
            var value = current.attr("value");
            var color = current.attr("color");
            linek.css('background', color);
            var choose_label = $("#choose_label");
            choose_label.find("li[value!='" + value + "']").removeClass(
                "selected");
            choose_label.find("a[value!='" + value + "']").removeAttr('style');
            var val_selct = $('#label_select_val');
            val_selct.val(value);
            val_selct.attr('name', current.attr('name'));
            val_selct.attr('color', color);
        },
        choose_ok : function(dom_id) {
            var desc = "";
            desc = $("#label_desc_record").attr("value");
            var val_selct = $('#label_select_val');
            var label = val_selct.val();
            if (!label) {
                $.alert(language.issue.chose_label_msg,
                    language.note.alert_title);
                return;
            }
            var color = val_selct.attr('color');
            var name = val_selct.attr('name');
            cdms.common.ajax_post(js_param.lable_change, {
                ids : js_param.issue_id,
                lv : label
            }, function(data) {
                var issue_label = $('#issue_label');
                issue_label.css({
                    'background-color' : color,
                    'border-color' : color
                });
                issue_label.html(name);
                document.getElementById("issue_label").title = desc;
                labels.close();
            });
         issue_view.reload();
        },
        cancel : function() {
            $('#issue_labels').layer().close();
        },
        open_labels : function() {
            labels.open();
        },


        priopity_f_click : function(dom_id, url, name, desc) {
            $("#icon_record").attr("value", url);
            $("#name_record").attr("value", name);
            $("#desc_record").attr("value", desc);
            var current = $('#' + dom_id);
            var linek = $('#' + dom_id + '_link');
            linek.addClass("selected");
            var value = current.attr("value");
            linek.addClass("linek");
            var choose_priopity = $("#choose_priopity");
            choose_priopity.find("li[value!='" + value + "']").removeClass(
                "selected");
            choose_priopity.find("a[value!='" + value + "']").removeAttr(
                'style');
            choose_priopity.find("a[value!='" + value + "']").removeClass(
                "linek");
            var val_selct = $('#priopity_select_val');
            val_selct.val(value);
            val_selct.attr('name', current.attr('name'));
        },
        // 点击提交按钮
        priopity2_choose_ok : function() {
            var val_selct = $('#priopity_select_val');
            var priopity = val_selct.val();
            if (!priopity) {
                $.alert(language.issue.chose_prioperty_msg,
                    language.note.alert_title);
                return;
            }
            var issue_id = "";
            issue_id = $("#issue_id_priopity").attr("value");
            var url = "";
            url = $("#icon_record").val();
            var name = "";
            name = $("#name_record").val();
            var desc = "";
            desc = $("#desc_record").val();
            cdms.common
                .ajax_post(
                js_param.priopity_change_url,
                {
                    ids : issue_id,
                    priopity : priopity
                },
                function(data) {
                    document.getElementById("issue_priopity").src = "/cdms/resources/common/images/"
                        + url;
                    $("#pri_name").html(name);
                    document.getElementById("pri_name").title = desc;
                    priopities.close();
                });
         issue_view.reload();
        },
        choose_priopity_close : function() {
            priopities.close();
        },
        open_priopities : function() {
            priopities.open();
        },
        /**
         * 绑定工具条事件
         */
        bindItem : function() {
            var toolbar = $('#action_toolbar').toolbar();
            var comment_toolbar;
            var status =$('#info_issue_issuestatus').attr('value') ;   //status :      0 : 打开,1：关闭，2：修复
            // issue_status为1时为问题已经关闭状态；反之，为打开状态
            if ( status== 1) {
                toolbar.ritems(0).attr('onclick',reopen_issue);
                comment_toolbar = toolbar.ritems(2);
            }else{
                //status 为0,2时（打开状态）
                comment_toolbar = toolbar.ritems(5);
                toolbar.ritems(0).attr('onclick',issue_view.close_issue);
                //绑定每个按纽  注意：修改下面按钮的个数时会影响最后一个回复按钮的绑定
                toolbar.ritems(1).attr("onclick", issue_view.open_priopities);
                toolbar.ritems(2).attr("onclick", issue_view.open_labels);
                toolbar.ritems(3).attr("onclick", function() {$('#assign_div').layer().open();});
                if(status == 0){
                    toolbar.ritems(4).attr("onclick",issue_view.fixed);
                    comment_toolbar = toolbar.ritems(6);
                }
            }

            comment_toolbar.attr("onclick", function() {
                window.location.href = '#answerform';
                // fixed cdms-57
                editor.focus();
            });

            cdms.common
                .ajax_get(
                js_param.view_issue_accounts_url
                    + js_param.issue_pid,
                function(accounts) {
                    var data = eval(accounts);
                    var html = '<input id="assgin_to" type="hidden" /><input id="assgin_to_name" type="hidden" />'
                        + '<table id="assign_table" style="height: 80%;width: 100%;table-layout:fixed">';
                    for ( var i = 0; i < data.length; i++) {
                        html += '<tr style="height: 20px;margin: 2px;border: 2px solid;background-color: #f1edff;cursor: pointer" id="{0}" ><td onclick="issue_view._choose_assign(\'{1}\',\'{2}\')"><a href="javascipt:;" style="text-decoration: none;color: #85848f; font-size: 14px ">{2}</a></td></tr>'
                            .format(data[i].login,
                            data[i].login, data[i].name);
                    }
                    html += "<tr></tr></table>";
                    html += "<button id='assign' width='100%' style='float:left' onclick='issue_view.asssign_submit()'><span><span>{0}</span></span></button>"
                        .format(language.issue.issue_assing_confirm);
                    html += "<button id='assign' width='100%' style='float:right' onclick='issue_view.close_layer(\"{0}\")'><span><span>{1}</span></span></button>"
                        .format("assign_div",
                        language.common.cancel);
                    var div_assign = $('#assign_div').layer({
                        singleton : true,
                        width : 120,
                        height : 200,
                        resizable : false,
                        movable : true,
                        maxable : false,
                        title : language.issue.issue_assign_title
                    });
                    div_assign.attr("contents", html);
                    assign_div = div_assign;

                });
        },
        /**
         * 修复问题功能函数
         * @param id
         */
        fixed :function(){
            fix_comment_layer.open();
            $("#fix_issue_comment_id").attr("value",js_param.issue_id);
            issue_view.create_kindeditor('fix_txt_answner');
        },

        /*
         *打开  问题关闭窗口的回复界面
         */
       close_issue : function() {
           close_comment_layer.open();
           issue_view.create_kindeditor('close_txt_answner');
        },

    /**关闭问题请求提交*/
    close_comment_submit : function(){
        var form_msg = $('#close_form_msg');
        form_msg.html("<span class='ajax_processing'>" + language.issue.issue_comment_submit_note + "</span>");
        if (kindeditor.isEmpty()) {
            $.alert(language.issue.issue_comment_empty_msg, language.note.alert_title);
            return false;
        }
        form_msg.show();
        var params = {'ids':js_param.issue_id,'content':kindeditor.html()};
        cdms.common.ajax_post(js_param.close_comment_submit_url,params,function(json){
            json = eval("("+json+")");
            if (json.type) {
                window.location.reload();
            } else {
                form_msg.html("<span class='error_msg'>" + json.msg + "</span>");
                form_msg.show();
            }
        });
    },
        /**
         * fix 反馈提交
         *
         */
        fix_comment_submit  : function(){
            var form_msg = $('#fix_form_msg');
            form_msg.html("<span class='ajax_processing'>" + language.issue.issue_comment_submit_note + "</span>");

            if (kindeditor.isEmpty()) {
                $.alert(language.issue.issue_comment_empty_msg, language.note.alert_title);
                return false;
            }
            form_msg.show();
            var id=$("#fix_issue_comment_id").attr("value");
            var content=kindeditor.html();
            var params ={"id":id,"content":content};
            cdms.common.ajax_post(js_param.fix_comment_submit_url,params,function(json){
                json = eval("("+json+")");
                if(json.type){
                         window.location.reload();
                }else{
                    form_msg.html("<span class='error_msg'>" + json.msg + "</span>");
                    form_msg.show();
                }
            });
        },
        /**
         * Close layer
         */
        close_layer          : function (id) {
            $("#" + id).layer().close();
            //todo  置空未生效，以后修改
            kindeditor.html("");
        },
        _choose_assign : function(assign, name) {
            $("#assign_table").find("tr[id !='" + assign + "']").css({
                backgroundColor : "#f1edff"
            });
            $("#" + assign).css({
                backgroundColor : "#C6A186",
                textDecorationColor : "white"
            });
            $("#assgin_to").attr("value", assign);
            $("#assgin_to_name").attr("value", name);
          issue_view.reload();
        },
        asssign_submit : function() {
            var assign_name = $("#assgin_to").attr("value");
            $("#assign_name").html($("#assgin_to_name").attr("value"));
            if (assign_name == "") {
                $.alert(language.issue.not_checked, language.note.alert_title);
                return false;
            }
            var param = {
                id : js_param.issue_id,
                name : assign_name
            };
            cdms.common.ajax_post(js_param.view_assign_submit, param, function(
                msg) {
                $("#assign_div").layer().close();
            });
          issue_view.reload();
        },
        /**根据提供的  textarea  id 创建 kindeditor*/
        create_kindeditor:function(layer_id){
                kindeditor = KindEditor.create('#'+layer_id, {
                    themeType            : 'default',
                    resizeType           : 0,
                    urlType              : 'domain',
                    shadowMode           : false,
                    allowPreviewEmoticons: false,
                    allowImageUpload     : true,
                    allowFlashUpload     : false,
                    uploadJson           : js_param.upload_url,
                    afterCreate          : function () {
                        KindEditor.ctrl(this.edit.iframe.get(0).contentWindow.document, 13, function () {
                            $('#'+layer_id).parent().submit();
                        });
                    },
                    afterChange          : function () {
                        this.sync();
                    },
                    items                : ['bold', 'italic', 'underline', 'strikethrough', 'removeformat', '|', 'insertorderedlist', 'insertunorderedlist',
                        'forecolor', 'hilitecolor', 'fontname', 'fontsize', '|', 'link', 'unlink', 'image', 'flash', 'quote', '|', 'source', 'about']
                });
        },
        /**comment grid 重新局部刷新*/
        reload:function(){
            $('#' + grid_id).grid().loadData();
        }
    }
}();
function show_img(image){
	$.block({"id":"2","message": "<img style='cursor:pointer' title='"+language.issue.img_back+"'onclick='javascript:$.unblock(2);' src='"+image.src+"'></img>" });

}
$(document)
    .ready(
    function() {
        cdms.common.jart_grid('issue_comment_grid', {
            rownumbers : false,
            showCheckBox : false,
            pageSize : 10,
            gridline : 'horizontal',
            idFields : 'id',
            showHead : false,
            url : js_param.comment_load_url + js_param.issue_id,
            emptyText : language.issue.issue_comment_empty_note,
            sortField : 'created',
            columns : [ [ {
                title : "",
                formatter : comment_formatter
            } ] ]
        });

        // 渲染工具条
        issue_view.bindItem();
        
        /**
         *
         * 格式化回复内容的信息
         *
         * @param item
         *            当前数据
         * @param index
         *            数据的位置
         */
        function comment_formatter(item) {
        	if(item.comment.content != null){
        		var resize_img = item.comment.content.replace('<img','<br /><img style="cursor:pointer" title="'+language.issue.img_title+'" onclick="show_img(this)"');
    			item.comment.content = resize_img;
        	}
        	
        	if(item.action==null){
        		 return '<div id="commnet-{0}" class="journal has-notes"><div id="note-{0}"><h4><a href="#note-{0}" class="right">#{0}</a>&nbsp;<a href="#">{3}</a> {4} {1}</h4><div class="wiki" id="commnet-{0}-notes"><p>{2}</p></div></div></div>'
               .format(item.comment_id, item.comment.created, item.comment.content,
                item.comment.uname,
                language.issue.issue_msg_commit);
        	} else if(item.action.action_type=='assignee'){
        		 return'<div id="commnet-{0}" class="journal has-notes"><div id="note-{0}"><h4><a href="#note-{0}" class="right">#{0}</a>&nbsp;{5}&nbsp;&nbsp;<a href="#">{3}</a>&nbsp;{1}&nbsp;{2}&nbsp;{6}&nbsp;<a href="#">{4}</a>'
               .format(item.comment_id,language.issue.action_at,item.action.action_time,item.action.action_username,item.action.new_value,
               item.action.action_type,language.issue.action_assignee);
        	}else if(item.action.action_type=='open'||item.action.action_type=='close'||item.action.action_type=='fixed'){
        		return'<div id="commnet-{0}" class="journal has-notes"><div id="note-{0}"><h4><a href="#note-{0}" class="right">#{0}</a>&nbsp;{3}&nbsp;&nbsp;<a href="#">{2}</a>&nbsp;{1}&nbsp{5}&nbsp;<a href="#">{3}</a>&nbsp;{4}'
        		.format(item.comment_id,language.issue.action_at,item.action.action_username,item.action.action_type,language.issue.issue_this,item.action.action_time)
        	}else{
        		return'<div id="commnet-{0}" class="journal has-notes"><div id="note-{0}"><h4><a href="#note-{0}" class="right">#{0}</a>&nbsp;{1}&nbsp;&nbsp;&nbsp;<a href="#">{2}&nbsp</a>{6}&nbsp;{7}&nbsp;{3}&nbsp;<a href="#">{1}</a>&nbsp;{5}&nbsp;<a href="#">{4}</a>'
        		.format(item.comment_id,item.action.action_type,item.action.action_username,language.issue.action_setlabel,item.action.new_value,language.issue.action_to,language.issue.action_at,item.action.action_time)
        	}
        }

        $('#form_answer')
            .ajaxForm(
            {
                dataType : 'json',
                beforeSerialize : function($form,
                                           options) {
                    editor.sync();
                },
                beforeSubmit : function() {
                    $('#btn_submit').attr('disabled',
                        'disabled');
                    if ($('#txt_answner').attr("value")
                        .trim().length == 0) {
                        $.alert(
                            language.issue.issue_comment_empty_msg,
                            language.note.alert_title);

                        $('#btn_submit').removeAttr("disabled");
                        return false;
                    }

                    var form_msg = $('#form_msg');
                    form_msg
                        .html("<span class='ajax_processing'>"
                        + language.issue.issue_comment_submit_note
                        + "</span>");
                    form_msg.show();
                },
                success : function(json) {
                    $('#btn_submit').removeAttr(
                        'disabled');
                    var form_msg = $('#form_msg');
                    if (json.type) {
                        form_msg.hide();
                        $('#form_answer').resetForm();
                        var comment = json.infos['comment'];
                        $('#issue_comment_grid').grid()
                            .loadData();
                        editor.html("");
                        $('#comments_span').show();
                        $("#comments").html(
                            json.infos.update);
                    } else {
                        form_msg
                            .html("<span class='error_msg'>"
                            + json.msg
                            + "</span>");
                        form_msg.show();
                    }
                }
            });
    });
